<template>
	<div class="ll-page">
		<div class="ll-page-container flex flex-col">
			<!-- S 查询 -->
			<div class="ll-page-container-query flex justify-between mb-2">
				<n-form
					inline
					:model="formValue"
					label-placement="left"
					:show-feedback="false"
					class="flex-1 flex-wrap"
				>
					<n-form-item label="邀请码：" path="value">
						<n-input
							v-model:value="formValue.code"
							placeholder="请输入邀请码"
							@update:value="handleSearch"
						></n-input>
					</n-form-item>
					<n-form-item label="邀请码有效期：" path="value">
						<n-date-picker
							v-model:value="formValue.termOfValidity"
							type="daterange"
							clearable
							@update:value="handleTermOfValidityChange"
						/>
					</n-form-item>
					<n-form-item label="发起人：" path="value">
						<n-input v-model:value="formValue.createUser" @update:value="handleSearch"></n-input>
					</n-form-item>
					<n-form-item label="合作方：" path="value">
						<n-input v-model:value="formValue.partnerName" @update:value="handleSearch"></n-input>
					</n-form-item>
					<n-form-item label="状态：" path="value">
						<n-select
							v-model:value="formValue.status"
							clearable
							:options="statusOptions"
							filterable
							class="w-193px"
							@update:value="handleSearch"
						/>
					</n-form-item>
					<n-form-item label="创建时间：" path="value">
						<n-date-picker
							v-model:value="formValue.createTime"
							type="daterange"
							clearable
							@update:value="handleCreateTimeChange"
						/>
					</n-form-item>
				</n-form>
				<div class="ll-page-container-query-btns">
					<n-button
						class="mr-1"
						color="rgba(0, 0, 0, 0.1)"
						text-color="#333333"
						@click="handelReset"
					>
						重置
					</n-button>
					<n-button color="#1D6FE9" text-color="#fff" @click="handelAdd">新增</n-button>
				</div>
			</div>
			<!-- S 表格 -->
			<div class="ll-page-container-table">
				<n-data-table
					:columns="columns"
					:data="tabelData"
					:pagination="pagination"
					:remote="true"
					:loading="tableLoading"
					size="small"
					flex-height
					:style="{ height: '100%' }"
				>
					<template #empty>
						<div class="flex flex-col items-center">
							<img style="height: 100px" src="@/assets/images/img_form_none@3x.png" alt="" />
							<span style="color: #666">暂无数据</span>
						</div>
					</template>
				</n-data-table>
			</div>
		</div>
		<!-- 新增编辑 -->
		<UpdateCode
			v-model:modal="updateDetailsModal"
			:detail-id="detailId"
			:title="addEditTitle"
			:update-type="updateType"
			@reload="handlePageReload"
		/>
		<n-modal
			v-model:show="toVoidModal"
			preset="card"
			style="width: 300px"
			title="作废"
			:bordered="false"
			:segmented="segmented"
		>
			作废邀请码将同时作废相关的福利！确认作废该邀请码？
			<template #footer>
				<div class="flex justify-end">
					<button class="close_btn" @click="toVoidModal = false">取消</button>
					<button class="confirm_btn ml-1" @click="handleToVoid">确认作废</button>
				</div>
			</template>
		</n-modal>
	</div>
</template>
<script setup>
import debounce from 'lodash/debounce';
import moment from 'moment';
import { h, ref, reactive, nextTick, watch } from 'vue';
import { NButton, useMessage, useDialog } from 'naive-ui';

import UpdateCode from './cmponents/UpdateCode.vue';

// 导入API接口
import { getList, cancelInvitationCode } from '@/api/invitationCodeManage';
import { useRoute, useRouter, onBeforeRouteUpdate } from 'vue-router';

let router = useRouter();
const route = useRoute();
const message = useMessage();
const dialog = useDialog();
const segmented = {
	content: 'soft',
	footer: 'soft'
};
// 查询条件
const formValue = reactive({
	pageIndex: 1,
	pageSize: 10,
	code: null,
	createEndTime: null,
	createStartTime: null,
	createUser: null,
	endTime: null,
	partnerName: null,
	startTime: null,
	status: null,
	termOfValidity: null,
	createTime: null
});

const cycleType = ref([
	{ value: 1, label: '每日' },
	{ value: 2, label: '每周' },
	{ value: 3, label: '每月' },
	{ value: 4, label: '每季度' },
	{ value: 5, label: '每年' },
	{ value: 9, label: '一次性' }
]);
const statusOptions = ref([
	{ label: '未使用', value: 0 },
	{ label: '已使用', value: 1 },
	{ label: '已过期', value: 2 },
	{ label: '已作废', value: 3 }
]);
// 邀请码有效期改变
// const termOfValidity = ref([]);
const handleTermOfValidityChange = (e) => {
	if (e) {
		formValue.startTime = moment(e[0]).format('YYYY-MM-DD') + ' 00:00:00';
		formValue.endTime = moment(e[1]).format('YYYY-MM-DD') + ' 23:59:59';
	} else {
		formValue.startTime = null;
		formValue.endTime = null;
	}
	handleSearch();
};
// 创建时间改变
// const createTime = ref([]);
const handleCreateTimeChange = (e) => {
	if (e) {
		formValue.createStartTime = moment(e[0]).format('YYYY-MM-DD') + ' 00:00:00';
		formValue.createEndTime = moment(e[1]).format('YYYY-MM-DD') + ' 23:59:59';
	} else {
		formValue.createStartTime = null;
		formValue.createEndTime = null;
	}
	handleSearch();
};
// 搜索
const handleSearch = debounce(() => {
	formValue.pageIndex = 1;
	fetchData();
}, 300);
// 表格
const columns = ref([
	{ title: '邀请码', width: '130px', key: 'code' },
	{
		title: '可享内容',
		width: '180px',
		render(row) {
			return [
				h('div', {}, `福利形式：  ${row.type === 1 ? '赠送素材资源' : '无'}`),
				h('div', {}, `福利周期：${row.cycleTypeStr}`)
			];
		}
	},
	{
		title: '邀请码有效期',
		width: '280px',
		render(row) {
			return [
				h(
					'div',
					{},
					` ${
						row.endTime === '2038-01-19 03:14:07'
							? '不限'
							: moment(row.startTime).format('YYYY/MM/DD') +
							  ' - ' +
							  moment(row.endTime).format('YYYY/MM/DD')
					}`
				)
			];
		}
	},
	{
		title: '状态',
		width: '80px',
		render(row) {
			return [
				h(
					'div',
					{
						style:
							row.status === 0
								? 'width: 46px;text-align: center;border-radius: 4px;font-size:12px;color:#1D6FE9;background: rgba(51, 102, 255, 0.08);'
								: row.status === 1
								? 'width: 46px;text-align: center;border-radius: 4px;font-size:12px;color:#57AE59;background: rgba(143, 179, 154, 0.08);'
								: row.status === 2
								? 'width: 46px;text-align: center;border-radius: 4px;font-size:12px;color:#F55F4E;background: rgba(179, 143, 143, 0.08);'
								: row.status === 3
								? 'width: 46px;text-align: center;border-radius: 4px;font-size:12px;color:#666666;background: rgba(163, 163, 163, 0.08);'
								: ''
					},
					row.statusStr
				)
			];
		}
	},
	{
		title: '使用次数',
		width: '80px',
		render(row) {
			return [h('div', {}, `${row.useCount}/${row.maxUse === -999 ? '不限' : row.maxUse}`)];
		}
	},
	{ title: '合作方', width: '150px', key: 'partnerName' },
	{ title: '创建人', width: '150px', key: 'createUser' },
	{
		title: '创建时间',
		width: '170px',
		render(row) {
			return [h('div', {}, `${moment(row.createTime).format('YYYY/MM/DD HH:mm:ss')}`)];
		}
	},
	{
		title: '操作',
		width: '160px',
		render(row, index) {
			return [
				h(
					NButton,
					{
						size: 'small',
						text: true,
						type: 'primary',
						style: {
							marginRight: '8px',
							fontSize: '14px',
							display: row.status === 2 || row.status === 3 ? 'none' : 'inline'
						},
						onClick: () => handelEdit(row)
					},
					{ default: () => '编辑' }
				),
				h(
					NButton,
					{
						size: 'small',
						text: true,
						type: 'primary',
						style: { marginRight: '8px', fontSize: '14px' },
						onClick: () =>
							router.push({
								path: '/invitationCodeManage/usage',
								query: { id: row.id },
								breadCrumbs: route.path
							})
					},
					{ default: () => '使用情况' }
				),
				h(
					NButton,
					{
						size: 'small',
						text: true,
						type: 'primary',
						style: {
							marginRight: '8px',
							fontSize: '14px',
							color: '#F55F4E',
							display: row.status === 3 ? 'none' : 'inline'
						},
						onClick: () => openToVoid(row)
					},
					{ default: () => '作废' }
				)
			];
		}
	}
]);
const tabelData = ref([]);
const tableLoading = ref(false);

// 分页
const pagination = reactive({
	page: 1,
	pageSize: formValue.pageSize,
	pageSizes: [10, 20, 30, 40],
	showSizePicker: true,
	itemCount: 0,
	prefix({ itemCount }) {
		return `共${itemCount}条`;
	},
	onChange: (page) => {
		pagination.page = page;
		formValue.pageIndex = page;
		fetchData();
	},
	onPageSizeChange: (pageSize) => {
		pagination.pageSize = pageSize;
		formValue.pageSize = pageSize;
		formValue.pageIndex = 1;
		pagination.page = 1;
		fetchData();
	}
});

// 获取数据
const fetchData = async () => {
	let res = null;
	tableLoading.value = true;
	if (router.currentRoute.value.fullPath === '/invitationCodeManage/invitationCodeManage') {
		let parmas = JSON.parse(JSON.stringify(formValue));
		delete parmas.termOfValidity;
		delete parmas.createTime;
		res = await getList(parmas);
	}
	tableLoading.value = false;
	if (res && res.code === 200) {
		tabelData.value = res.data.invitationCodeList || [];
		pagination.itemCount = res.data.total || 0;
	}
};

// 重置
const handelReset = () => {
	resetData();
	fetchData();
};

// 初始化数据
const initData = async () => {
	await fetchData();
};

// 初始化数据
const resetData = () => {
	formValue.pageIndex = 1;
	formValue.pageSize = 10;
	formValue.code = null;
	formValue.createEndTime = null;
	formValue.createStartTime = null;
	formValue.createUser = null;
	formValue.endTime = null;
	formValue.partnerName = null;
	formValue.startTime = null;
	formValue.status = null;
	formValue.partnerName = null;
	formValue.termOfValidity = null;
	formValue.createTime = null;
	// 重置分页
	pagination.page = 1;
	// 弹框
	updateDetailsModal.value = false;
	addEditTitle.value = '';
	// 作废弹框
	toVoidModal.value = false;
};

nextTick(() => {
	initData();
});

const handlePageReload = () => {
	fetchData();
};
// 监听路由变化
watch(
	() => route.fullPath,
	(n, o) => {
		pagination.page = 1;
		resetData();
		initData();
	}
);
const updateType = ref(0);
// 新增
const updateDetailsModal = ref(false);
const addEditTitle = ref('');
const handelAdd = () => {
	updateType.value = 1;
	updateDetailsModal.value = true;
	addEditTitle.value = '新增';
};
// 编辑
const detailId = ref(0);
const handelEdit = (row) => {
	updateType.value = 2;
	updateDetailsModal.value = true;
	addEditTitle.value = '编辑';
	detailId.value = row.id;
};
// 作废
const toVoidModal = ref(false);
const id = ref(0);
const openToVoid = (row) => {
	toVoidModal.value = true;
	id.value = row.id;
};
const handleToVoid = async () => {
	let res = null;
	res = await cancelInvitationCode({ id: id.value });
	if (res.code === 200) {
		toVoidModal.value = false;
		message.success('操作成功');
		fetchData();
	}
};
</script>

<style lang="less" scoped>
.ll-page {
	padding: 10px;
	overflow-x: auto;
	display: -webkit-box;
	height: 100%;
	background-color: #ffffff;
	&-container {
		height: 100%;
		&-query {
			padding: 0 12px 9px;
			background: #f5f5f5;
			border-radius: 4px;
			border: 1px solid #f0f0f0;
			&-btns {
				margin-top: 9px;
			}
			.n-form.n-form--inline .n-form-item {
				margin-top: 9px;
			}
		}
		&-table {
			overflow: hidden;
			flex: 1 1 0%;
		}
	}
}
.close_btn {
	font-size: 13px;
	font-family: PingFangSC-Regular, PingFang SC;
	font-weight: 400;
	width: 80px;
	height: 32px;
	background: #ddd;
	border-radius: 4px;
}
.confirm_btn {
	font-size: 13px;
	font-family: PingFangSC-Medium, PingFang SC;
	color: #ffffff;
	width: 93px;
	height: 32px;
	background: #f55f4e;
	border-radius: 4px;
}

.flex {
	display: -webkit-box;
	display: -ms-flexbox;
	display: -webkit-flex;
	display: flex;
}
.flex-col {
	-webkit-box-orient: vertical;
	-webkit-box-direction: normal;
	-ms-flex-direction: column;
	-webkit-flex-direction: column;
	flex-direction: column;
}
.flex-1 {
	-webkit-box-flex: 1;
	-ms-flex: 1 1 0%;
	-webkit-flex: 1 1 0%;
	flex: 1 1 0%;
}
.flex-wrap {
	-ms-flex-wrap: wrap;
	-webkit-flex-wrap: wrap;
	flex-wrap: wrap;
}
.items-center {
	-webkit-box-align: center;
	-ms-flex-align: center;
	-webkit-align-items: center;
	align-items: center;
}
.justify-between {
	-webkit-box-pack: justify;
	-ms-flex-pack: justify;
	-webkit-justify-content: space-between;
	justify-content: space-between;
}
.justify-end {
	-webkit-box-pack: end;
	-ms-flex-pack: end;
	-webkit-justify-content: flex-end;
	justify-content: flex-end;
}
.mt-1 {
	margin-top: 0.25rem; /* 4px */
}
.mt-2 {
	margin-top: 0.5rem; /* 8px */
}
.ml-1 {
	margin-left: 0.25rem; /* 4px */
}
.mr-1 {
	margin-right: 0.25rem; /* 4px */
}
.mb-2 {
	margin-bottom: 0.5rem; /* 8px */
}
</style>
